package cn.mdmbct.spring.starter.douyin.enterprise.config;

import cn.mdmbct.douyin.common.config.HttpConfig;
import cn.mdmbct.douyin.common.http.apache.ApacheHttpExecutorFactory;
import cn.mdmbct.douyin.common.http.okhttp.OkHttpExecutorFactory;
import cn.mdmbct.douyin.common.storage.DyStorageManager;
import cn.mdmbct.douyin.enterprise.service.DyEnterpriseServiceImpl;
import cn.mdmbct.douyin.enterprise.service.interfaces.DyEnterpriseService;
import cn.mdmbct.spring.starter.douyin.common.properties.dy.DyOpenApiProperties;
import cn.mdmbct.spring.starter.douyin.common.properties.dy.HttpProperties;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author mdmbct  mdmbct@outlook.com
 * @date 2021/3/19 22:20
 * @modified mdmbct
 * @since 1.0
 */
@Configuration
public class DyOpenApiEnterpriseServiceAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public DyEnterpriseService dyEnterpriseService(DyOpenApiProperties apiProperties, DyStorageManager storageManager) {

        HttpProperties httpProperties = apiProperties.getHttp();
        HttpConfig httpConfig = new HttpConfig();
        BeanUtils.copyProperties(httpProperties, httpConfig);
        switch (httpProperties.getType()) {
            case OK_HTTP:
                return getDyEnterpriseServiceWithOkHttp(httpConfig, storageManager);
            case APACHE_HTTP:
                return getDyEnterpriseServiceWithApacheHttp(httpConfig, storageManager);
            default:
                return getDefaultDyEnterpriseServiceImpl(httpConfig, storageManager);
        }
    }


    private DyEnterpriseService getDyEnterpriseServiceWithOkHttp(HttpConfig httpConfig, DyStorageManager storageManager) {

        return new DyEnterpriseServiceImpl(storageManager, new OkHttpExecutorFactory().createHttpExecutor(httpConfig));
    }

    private DyEnterpriseService getDyEnterpriseServiceWithApacheHttp(HttpConfig httpConfig, DyStorageManager storageManager) {
        return new DyEnterpriseServiceImpl(storageManager, new ApacheHttpExecutorFactory().createHttpExecutor(httpConfig));
    }

    private DyEnterpriseService getDefaultDyEnterpriseServiceImpl(HttpConfig httpConfig, DyStorageManager storageManager) {
        return getDyEnterpriseServiceWithOkHttp(httpConfig, storageManager);
    }
}
